#include "hal_data.h"
#include <stdio.h>

volatile bool uart4_tx_complete = false;

uint8_t recv_buffer[20] = {0};
uint8_t recv_len = 0;
//初始化uart4
void uart4_init(void)
{
    /* Open the transfer instance with initial configuration. */
    fsp_err_t err = R_SCI_UART_Open(&g_uart4_ctrl, &g_uart4_cfg);
    assert(FSP_SUCCESS == err);	
}

/* uart4中断回调函数 */
void uart4_callback (uart_callback_args_t * p_args)
{
    /* Handle the UART event */
    switch (p_args->event)
    {
        /* Received a character */
        case UART_EVENT_RX_CHAR:
        {
				    recv_buffer[recv_len] = (uint8_t) p_args->data;
            R_SCI_UART_Write(&g_uart4_ctrl, &recv_buffer[recv_len], 1);
					  recv_len++;
					  if(recv_len >= 20)
						{
							recv_len = 0;
						}
            break;
        }
        /* Receive complete */
        case UART_EVENT_RX_COMPLETE:
        {
            //uart4_tx_complete = true;
            break;
        }
        /* Transmit complete */
        case UART_EVENT_TX_COMPLETE:
        {
            uart4_tx_complete = true;
            break;
        }
        default:
        {
        }
    }
}

//初始化uart5
void uart5_init(void)
{
    /* Open the transfer instance with initial configuration. */
    fsp_err_t err = R_SCI_UART_Open(&g_uart5_ctrl, &g_uart5_cfg);
    assert(FSP_SUCCESS == err);	
}

/* uart4中断回调函数 */
void uart5_callback (uart_callback_args_t * p_args)
{
    /* Handle the UART event */
    switch (p_args->event)
    {
        /* Received a character */
        case UART_EVENT_RX_CHAR:
        {
				    recv_buffer[recv_len] = (uint8_t) p_args->data;
            R_SCI_UART_Write(&g_uart4_ctrl, &recv_buffer[recv_len], 1);
					  recv_len++;
					  if(recv_len >= 20)
						{
							recv_len = 0;
						}
            break;
        }
        /* Receive complete */
        case UART_EVENT_RX_COMPLETE:
        {
            //uart4_tx_complete = true;
            break;
        }
        /* Transmit complete */
        case UART_EVENT_TX_COMPLETE:
        {
            //uart4_tx_complete = true;
            break;
        }
        default:
        {
        }
    }
}


/* 重定向 printf 输出 */
#if defined __GNUC__ && !defined __clang__
int _write(int fd, char *pBuffer, int size); //防止编译警告
int _write(int fd, char *pBuffer, int size)
{
   (void)fd;
   R_SCI_UART_Write(&g_uart4_ctrl, (uint8_t *)pBuffer, (uint32_t)size);
   while(uart_send_complete_flag == false);
   uart_send_complete_flag = false;

   return size;
}
#else
int fputc(int ch, FILE *f)
{
   (void)f;
   R_SCI_UART_Write(&g_uart4_ctrl, (uint8_t *)&ch, 1);
   while(uart4_tx_complete == false);
   uart4_tx_complete = false;

   return ch;
}
#endif